package com.hpf.springcloud.controller;

import com.hpf.commons.pojo.Payment;
import com.hpf.commons.utils.CommonResult;
import com.hpf.commons.enums.ResultCode;
import com.hpf.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @description: 支付控制层
 * @datetime: 2020/8/14 23:44
 * @author: huangpengfei
 */
@RestController
@Slf4j
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    @Autowired
    private DiscoveryClient discoveryClient;

    @PostMapping(value = "/payment/create")
    public CommonResult create(@RequestBody Payment payment) {
        int result = paymentService.create(payment);
        if (result > 0) {
            return new CommonResult(ResultCode.SUCCESS.getCode(), "插入数据库成功,serverPort：" + serverPort, result);
        } else {
            return new CommonResult(ResultCode.FAIL.getCode(), "插入数据库失败", result);
        }
    }

    @GetMapping(value = "/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id) {
        Payment payment = paymentService.getPaymentById(id);
        if (payment != null) {
            return new CommonResult(ResultCode.SUCCESS.getCode(), "查询成功,serverPort：" + serverPort, payment);
        } else {
            return new CommonResult(ResultCode.FAIL.getCode(), "没有对应记录", id);
        }
    }

    @GetMapping(value = "/payment/discovery")
    public CommonResult discovery() {
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("service--->" + service);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info(instance.getInstanceId() + "--" + instance.getHost() + "--" + instance.getPort() + "--" + instance.getUri() + "--" + instance.getServiceId());
        }
        return null;
    }

    @GetMapping(value = "/payment/port")
    public String getPort() {
        return serverPort;
    }

    @GetMapping(value = "/payment/zipkin")
    public String zipkin() {
        return "hello zipkin";
    }

    @GetMapping(value = "/payment/feign/timeout")
    public String feignTimeout() {
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }
}
